<template>
  <el-table border stripe :data="fileData">
    <el-table-column
      v-for="(column,index) in fileColumn"
      :key="index"
      :label="column.label"
      :width="column.width"
      :align="column.align"
    >
      <template slot-scope="scope">
        <div v-if="column.prop==='name'">
          <span v-for="(file, fileIndex) in scope.row.fileList" :key="file.name || file.oldFileName" class="file-item">
            <a v-if="file.oldFileName" class="download-link" :href="`/comm-file-server/file/download?fileId=${file.id}`">
              <!-- <span>{{ `${file.oldFileName}${fileIndex === scope.row.fileList.length - 1? '': '; '}` }}</span> -->
              <span>{{ `${file.oldFileName}` }}</span>
            </a>
            <span v-else>
              <span>{{ `${file.name}` }}</span>
            </span>
            <i v-if="!checkFlag" class="el-icon-close" @click="fakeDeleteFile(scope.row, file, fileIndex)" />
            <span>{{ `${fileIndex === scope.row.fileList.length - 1? '': '；'}` }}</span>
          </span>
        </div>
        <div v-else>
          <span>{{ scope.row[column.prop] }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column
      v-if="!checkFlag"
      label="操作"
      width="80"
      align="center"
    >
      <template slot-scope="scope">
        <el-upload
          :ref="`commonUpload${scope.row.refStr}`"
          :action="`?businessId=${scope.row.businessId}&sysCode=personManage&businessNode=${scope.row.businessNode}`"
          :auto-upload="false"
          multiple
          :on-change="fileChange(scope.row, scope.$index)"
          :show-file-list="false"
          :with-credentials="true"
          :http-request="upload"
          :accept="getAcceptType()"
          :limit="scope.row.limit || 10"
          :on-exceed="(files, fileList)=>handleExceed(files, fileList,scope.row.limit)"
          :file-list="scope.row.fileList"
        >
          <el-button size="mini-1" type="text">上传</el-button>
        </el-upload>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import { fileColumn } from './data'
import { handleChange2 } from '@/utils'
import { upload, deleteFile } from '@/api/app'
export default {
  props: {
    fileData: {
      type: Array,
      default: () => {
        return []
      }
    },
    checkFlag: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileColumn,
      deleteFileList: [],
      uploadPromise: [],
      deletePromise: []
    }
  },
  methods: {
    handleExceed(files, fileList, limit) {
      if (!limit) {
        limit = 10
      }
      this.$my_message.warning(`文件数量不能超过${limit}个`)
    },
    fileChange(row, index) {
      return (file, fileList) => {
        this.fileData[index].currentFileList = fileList
        if (file.status === 'ready') {
          // 校验文件大小
          if (!(file.size / 1024 / 1024 < 5)) {
            this.$my_message.warning('上传材料大小不能超过5MB!')
            return fileList.pop()
          }
          // 校验文件大小
          if (file.size === 0) {
            this.$my_message.warning('上传文件不能为空')
            return fileList.pop()
          }
          this.fileData[index].fileList.push(file)
          handleChange2(file, this.fileData[index].fileList)
        }
        if (file.status === 'fail') {
          // 如果文件上传失败，将文件从展示的文件列表中删除
          const fileIndex = this.fileData[index].fileList.findIndex(f => f.name === file.name)
          this.fileData[index].fileList.splice(fileIndex, 1)
        }
      }
    },
    upload(params) {
      const formData = new FormData()
      formData.append('file', params.file)
      const req = upload(params.action, formData).then(res => {
        const data = res.data
        params.onSuccess(data)
        return data
      }).catch((err) => {
        params.onError(err)
        return Promise.reject(err)
      })
      this.uploadPromise.push(req)
    },
    deleteFile(fileId, index) {
      return deleteFile({
        fileId
      }).then(res => {
        this.deleteFileList.splice(index, 1)
        return Promise.resolve(res)
      })
    },
    // 页面删除
    fakeDeleteFile(row, file, index) {
      if (file.oldFileName || file.id) {
        // 如果是已上传的文件，先记录到数组中，等保存或提交时再调用接口删除
        this.deleteFileList.push(file)
      } else if (file.response && (file.response.id || file.response.data.id)) {
        this.deleteFileList.push({ ...file, id: file.response.id || file.response.data.id })
      } else {
        // 如果是待上传的文件，需要在上传文件的组件中将该文件删除
        const fileInx = row.currentFileList.findIndex(item => item.name === file.name)
        row.currentFileList.splice(fileInx, 1)
      }
      // 页面中删除
      row.fileList.splice(index, 1)
    },
    uploadReq() {
      this.fileData.map(item => {
        this.$refs[`commonUpload${item.refStr}`].submit()
      })
    },
    deleteReq() {
      this.deleteFileList.map((item, index) => {
        this.deletePromise.push(this.deleteFile(item.id, index))
      })
    },
    submit(draft) {
      this.deletePromise = []
      if (draft) {
        this.deleteReq()
      }
      return Promise.all(this.deletePromise).then(() => {
        this.uploadReq()
        return Promise.all(this.uploadPromise).then(res => {
          return Promise.resolve(res)
        }).catch(() => {
          return Promise.reject('upload error')
        })
      }).catch((err) => {
        console.log('err', err)
        return Promise.reject('delete error')
      })
    },
    getAcceptType() {
      return this.$route.query.type === 'basicPage' ? 'image/*' : ''
    }
  }
}
</script>

<style lang="scss" scoped>
// .file-item{
//   margin-right: 5px;
// }

</style>
